<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>刮刮卡 v4 自动显示</title>
<style>
body{
    margin:0;
    display:flex;
    justify-content:center;
    align-items:center;
    height:100vh;
    background:#ffa500;
    font-family:"Comic Sans MS";
}
.card-container{
    position:relative;
    width:400px; height:300px;
    border:3px dashed #ff4500;
    border-radius:10px;
    overflow:hidden;
    box-shadow:0 0 15px rgba(0,0,0,0.3);
}
.card-container img{
    width:100%; height:100%;
}
canvas{
    position:absolute; top:0; left:0;
    cursor:pointer;
}
.hint{
    position:absolute;
    bottom:5px; left:50%;
    transform:translateX(-50%);
    background:rgba(255,69,0,0.8);
    color:#fff;
    padding:3px 6px;
    border-radius:4px;
    font-size:14px;
}
</style>
</head>
<body>
<div class="card-container">
    <img src="./images/prize4.gif" alt="奖励图片">
    <canvas id="canvas" width="400" height="300"></canvas>
</div>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// 涂层颜色
ctx.fillStyle = "#ffcc99";
ctx.fillRect(0,0,canvas.width,canvas.height);

let isFading = false; // 是否正在渐隐

function scratch(x, y){
    ctx.globalCompositeOperation = "destination-out";
    ctx.beginPath();
    ctx.arc(x, y, 12, 0, Math.PI*2);
    ctx.fill();
}

// 计算刮开比例
function getScratchedRatio(){
    const data = ctx.getImageData(0,0,canvas.width,canvas.height).data;
    let total = data.length/4;
    let cleared = 0;
    for(let i=3;i<data.length;i+=4){
        if(data[i]===0) cleared++;
    }
    return cleared/total;
}

// 渐隐动画
function fadeOut(){
    if(!isFading) return;
    ctx.globalAlpha -= 0.05;
    if(ctx.globalAlpha <= 0){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        canvas.style.display = "none";
        return;
    }
    ctx.fillStyle = "#ffcc99";
    ctx.fillRect(0,0,canvas.width,canvas.height);
    requestAnimationFrame(fadeOut);
}

// 鼠标事件
canvas.addEventListener("mousemove", e=>{
    if(e.buttons===1 && !isFading){
        const r = canvas.getBoundingClientRect();
        const x = e.clientX - r.left;
        const y = e.clientY - r.top;
        scratch(x, y);
        if(getScratchedRatio()>=0.2){
            isFading = true;
            ctx.globalAlpha = 1;
            fadeOut();
        }
    }
});

// 触摸事件
canvas.addEventListener("touchmove", e=>{
    e.preventDefault();
    if(isFading) return;
    const r = canvas.getBoundingClientRect();
    const t = e.touches[0];
    const x = t.clientX - r.left;
    const y = t.clientY - r.top;
    scratch(x, y);
    if(getScratchedRatio()>=0.2){
        isFading = true;
        ctx.globalAlpha = 1;
        fadeOut();
    }
},{passive:false});
</script>
</body>
</html>
